// 获取搜索元素
const pop = document.getElementById('pop');
const popTitle = document.getElementById('popTitle');
const title = document.getElementById('title');
const des = document.getElementById('des');
const lists = document.getElementById('lists');
const keyword = document.getElementById('keyword');

const search = () => {
    let keywordVal = keyword.value.toLowerCase(); // 转为小写进行搜索
    let items = lists.querySelectorAll(".list");
    for (let item of items) {
        let itemTitle = item.querySelector(".list-title").innerText.toLowerCase(); // 转为小写
        let itemDes = item.querySelector(".list-des").innerText.toLowerCase(); // 转为小写
        item.style.display = (itemTitle.includes(keywordVal) || itemDes.includes(keywordVal)) ? "block" : "none";
    }
}

const changePop = (t = '添加', list = null, isedit = false) => {
    pop.style.visibility = "visible";
    pop.style.opacity = 1;
    popTitle.innerText = t;
    isformedit = isedit;

    if (isformedit) {
        listIdx = list.idx;
        title.value = list.title;
        des.value = list.des;
    } else {
        title.value = '';
        des.value = '';
    }
}

let isformedit = false;
let listIdx;

const cancel = () => {
    pop.style.visibility = "hidden";
    pop.style.opacity = 0;
}

const save = () => {
    if (title.value) { 
        if (isformedit) {
            let list = document.getElementById(`lists${listIdx}`);
            list.querySelector(`.list-title`).innerText = title.value;
            list.querySelector(`.list-des`).innerText = des.value;
        } else {
            let listLength = lists.querySelectorAll('.list').length;
            let listForm = JSON.stringify({
                idx: listLength,
                title: title.value,
                des: des.value
            });
            lists.innerHTML += `
                <li class="list" id="lists${listLength}">
                    <div class="flex-justify-between">
                        <div class="list-title">${title.value}</div>
                        <button onclick='changePop("编辑", ${listForm}, true)' class="edit">编辑</button>
                    </div>
                    <div class="list-des">${des.value}</div>
                    <div class="flex-justify-between1">
                        <div class="list-time">${getNowTime()}</div>
                        <button onclick="del(${listLength})" class="del">删除</button>
                    </div>
                </li>`;
        }
        cancel();
    } else {
        alert("请添加标题！");
    }
}

const getNowTime = () => {
    let time = new Date();
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate(); // 修正为 getDate


    const setZero = (t) => (t >= 10 ? t : '0' + t);

    return `${year}-${setZero(month)}-${setZero(day)} `;
}

const del = (i) => {
    const item = lists.querySelector(`#lists${i}`);
    if (item) {
        lists.removeChild(item);
    }
}
